package com.kool.kmetrics.metrics;

import com.alibaba.fastjson.JSON;
import com.kool.kmetrics.bean.SubscriptionSnapshotDo;
import com.kool.kmetrics.common.constant.ErrorCode;
import com.kool.kmetrics.common.exception.AppException;
import com.kool.kmetrics.consumer.vo.Subscription;
import com.kool.kmetrics.consumer.vo.SubscriptionsLog;
import com.kool.kmetrics.dao.SubscriptionSnapshotDao;
import com.kool.kmetrics.common.util.DateUtil;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author luyu
 */
@Component
public class SubscriptionComputer implements MetricsComputer {
    @Resource
    private SubscriptionSnapshotDao subscriptionSnapshotDao;

    @Override
    public void compute(String log) {
        SubscriptionsLog subscriptionsLog = JSON.parseObject(log, SubscriptionsLog.class);
        String timestamp = subscriptionsLog.getTimestamp();
        List<Subscription> subscriptions = subscriptionsLog.getSubscriptions();

        List<SubscriptionSnapshotDo> subscriptionSnapshotDos = new ArrayList<>();
        if (subscriptions != null) {
            for (Subscription subscription : subscriptions) {
                SubscriptionSnapshotDo subscriptionSnapshotDo = new SubscriptionSnapshotDo();
                try {
                    subscriptionSnapshotDo.setClientId(subscription.getClientId())
                            .setSnapshotTime(DateUtil.parseDate(timestamp, DateUtil.DateFormatEnum.DEFAULT.getFormat()))
                            .setQos(subscription.getQos())
                            .setTopicFilter(subscription.getTopicFilter());
                } catch (ParseException e) {
                    throw new AppException(ErrorCode.BUSINESS_ERROR, e, e.getMessage());
                }

                subscriptionSnapshotDos.add(subscriptionSnapshotDo);
            }
        }

        //保存到快照表
        subscriptionSnapshotDao.batchInsert(subscriptionSnapshotDos);
    }
}
